import type { RoleTable } from '@/types/role'
import type { MenuTable } from '@/types/menu'
const TokenKey = 'token'
const UserInfoKey = 'user_info'
const UserRoleNamesKey = 'user_roles'
const UserMenuStoryKey = 'user_menus'
/**
 * 获取token
 * @returns token
 */
export function getJwt() {
  return localStorage.getItem(TokenKey)
}
/**
 * 设置token
 * @param token 登陆时传过来的token值
 */
export function setJwt(token: string) {
  localStorage.setItem(TokenKey, token)
}

/**
 * 深拷贝工具函数
 * 只能拷贝能够进行JSON转换的数据
 * @param data 需要拷贝的数据
 * @returns
 */
export function deepCopy<T>(data: T) {
  return JSON.parse(JSON.stringify(data)) as T
}
/**
 * 持久化用户的角色
 * @param roleNames 用户的角色集合
 */
export function setUserRoleNames(roleNames: RoleTable[]) {
  localStorage.setItem(UserRoleNamesKey, JSON.stringify(roleNames))
}
/**
 * 获取用户持久化的角色集合
 * @returns 角色集合
 */
export function getUserRoleNames() {
  let roles = localStorage.getItem(UserRoleNamesKey)
  if (roles) {
    return JSON.parse(roles) as RoleTable[]
  }
  return []
}
/**
 * 获取用户选择的角色id
 * @returns 用户选择登录的角色id
 */
export function getUseRoleId(): number | null {
  let uid = getJwt()
  if (uid) {
    let userInfo = uid.split('.')[1]
    userInfo = atob(userInfo)
    userInfo = JSON.parse(userInfo)
    if ((userInfo as any)['rid']) {
      return (userInfo as any)['rid']
    }
    return null
  }
  return null
}

/**
 * 菜单数据持久化
 * @param menus 登陆时获取到的菜单信息
 */
export function setUserMenus(menus: MenuTable[]) {
  localStorage.setItem(UserMenuStoryKey, JSON.stringify(menus))
}
/**
 * 获取持久化的菜单信息
 * @returns 用户菜单信息
 */
export function getUserMenus(): MenuTable[] {
  let menus = localStorage.getItem(UserMenuStoryKey)
  if (menus) {
    return JSON.parse(menus)
  }
  return []
}
/**
 * 清除用户信息
 */
export function clearAllInfo() {
  localStorage.removeItem(TokenKey)
  localStorage.removeItem(UserRoleNamesKey)
  localStorage.removeItem(UserInfoKey)
}

export function authXSS(str: string): string {
  return str
    .replaceAll(/<script\b[^>]*>(.*?)<\/script>/gi, '')
    .replaceAll(/ on\w+="[^"]*"/g, '')
    .replaceAll(/javascript:[^'"\s;]+/gi, '')
}
